﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Net;
using System.Windows.Forms;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using System.Diagnostics;
using System.Resources;
using System.Reflection;

namespace HttpDownloader
{
    public partial class Form1 : Form
    {
        private int m_iNumConnections = 2;
        private string m_pStrProxy = "";
        private string m_pStrPort = "";
        private string m_pStrUrl = "";
        private string m_pStrFilePath = "";
        List<MyDownload> lstObjMyDownload;
        MyDownload tempMyDownload = new MyDownload();
        private bool isClickCell = false;
        private bool isPause = false;
        public bool isExit = false;
        Setting m_pFrmSetting = new Setting();
        private int ixdSelect = 0;

        readonly object syncLock = new object();

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            lstObjMyDownload = new List<MyDownload>();
        }

        public ListView getListView()
        {
            return m_pLstView;
        }

        private void m_pBtnAddUrl_Click(object sender, EventArgs e)
        {
            m_pBtnResume.Enabled = true;
            AddURL formAddURL = new AddURL();
            formAddURL.ShowDialog();
            if (!formAddURL.strUrl.Equals(""))
            {
                m_pStrUrl = formAddURL.strUrl;
                m_pStrFilePath = formAddURL.strFilePath;
                if (m_pStrUrl.StartsWith("http://", StringComparison.OrdinalIgnoreCase) == false)
                {
                    m_pStrUrl = "http://" + m_pStrUrl;
                }               
                StartDownload();
            }
        }

        private void StartDownload()
        {
            MyDownload myDownload = new MyDownload(m_pStrUrl, m_pStrFilePath, m_pStrProxy, m_pStrPort, m_iNumConnections);
            lstObjMyDownload.Add(myDownload);
            myDownload.OnUpdateListView += new EventHandler(myDownload_UpdateListView);
            myDownload.myHttpDownload();
        }

        public void myDownload_UpdateListView(object sender, EventArgs e)
        {
            lock (syncLock)
            {
                List<object> lst = (List<object>)sender;
                isExit = false;
                for (int i = 0; i < m_pLstView.Items.Count; i++)
                {
                    if (m_pLstView.Items[i].SubItems[0].Text.Equals(lst.ElementAt(0).ToString()))
                    {
                        isExit = true;
                        try
                        {
                            m_pLstView.Items[i] = (ListViewItem)lst.ElementAt(1);
                        }
                        catch (System.Exception ex)
                        {
                        	
                        }                      
                        return;
                    }
                }

                if (!isExit)
                {
                    m_pLstView.Items.Add((ListViewItem)lst.ElementAt(1));
                }
            }
        }
        
        private void m_pBtnSetting_Click(object sender, EventArgs e)
        {
            m_pFrmSetting.ShowDialog();
            m_pStrPort = m_pFrmSetting.m_pStrPort;
            m_pStrProxy = m_pFrmSetting.m_pStrProxy;
            m_iNumConnections = m_pFrmSetting.m_iNumberConnects;
        }

        private void m_pLstView_DoubleClick(object sender, EventArgs e)
        {
            if (m_pLstView.Items.Count > 0)
            {
                int intselectedindex = m_pLstView.SelectedIndices[0];
                if (intselectedindex >= 0)
                {
                    lstObjMyDownload.ElementAt<MyDownload>(intselectedindex).ShowDownloadProcess();
                }
            }
        }

        private void m_pLstView_Click(object sender, EventArgs e)
        {
            if (m_pLstView.Items.Count > 0)
            {
                try
                {
                    ixdSelect = m_pLstView.SelectedIndices[0];
                    tempMyDownload = lstObjMyDownload.ElementAt<MyDownload>(ixdSelect);
                    isClickCell = true;
                    m_pBtnResume.Enabled = true;
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show("Chon lai nha, Click vao ten file!");
                    isClickCell = false;
                }
            }
        }

        private void m_pBtnResume_Click(object sender, EventArgs e)
        {
            

            if (!isClickCell)
            {
                MessageBox.Show("Hay chon 1 phan tu download");
                return;
            }

            if (!isPause)
            {
                isPause = true;
                this.m_pBtnResume.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.Resume));
                tempMyDownload.Pause();             
            }
            else
            {
                isPause = false;
                this.m_pBtnResume.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.Pause));
                tempMyDownload.Resume();
            }
            isClickCell = false;
        }

        private void m_pBtnStop_Click(object sender, EventArgs e)
        {
            if (!isClickCell)
            {
                MessageBox.Show("Hay chon 1 phan tu download");
                return;
            }

            m_pBtnResume.Enabled = false;
            tempMyDownload.Stop();
            isClickCell = false;
        }

        private void m_pBtnDelete_Click(object sender, EventArgs e)
        {
            bool isFileExit = false;
            if (!isClickCell)
            {
                MessageBox.Show("Hay chon 1 phan tu download");
                return;
            }
            isFileExit = File.Exists(tempMyDownload.StrFilePath);
            if (!isFileExit)
            {
                m_pLstView.Items.Remove(m_pLstView.Items[ixdSelect]);
                return;
            }
            if (!tempMyDownload.isFinishDownload)  //khong cho xoa nhung file dang download
            {
                return;
            }
            try
            {
                m_pLstView.Items.Remove(m_pLstView.Items[ixdSelect]);
                if (isFileExit)
                {
                    File.Delete(tempMyDownload.StrFilePath);
                }
                lstObjMyDownload.Remove(tempMyDownload);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Khong the xoa file " + tempMyDownload.StrFilePath + " do file dang duoc mo.");
            }

        }

        private void m_pBtnStopAll_Click(object sender, EventArgs e)
        {
            int n = m_pLstView.Items.Count;
            for (int i = 0; i < n; i++ )
            {
                tempMyDownload = lstObjMyDownload.ElementAt<MyDownload>(i);
                tempMyDownload.Stop();
            }
            isClickCell = false;
            m_pBtnResume.Enabled = false;
        }
        private void m_pBtnDeleteAll_Click(object sender, EventArgs e)
        {
            int n = m_pLstView.Items.Count;
            int ixdElement = 0;
            for (int i = 0; i < n; i++)
            {
                tempMyDownload = lstObjMyDownload.ElementAt<MyDownload>(ixdElement);
                if (!tempMyDownload.isFinishDownload)  //khong cho xoa nhung file dang download
                {
                    ixdElement++;
                    continue;
                }
                m_pLstView.Items.Remove(m_pLstView.Items[ixdElement]);
                if (File.Exists(tempMyDownload.StrFilePath))
                {
                    try
                    {
                        File.Delete(tempMyDownload.StrFilePath);
                    }
                    catch (System.Exception ex)
                    {
                        MessageBox.Show("File chua duoc xoa do co ung dung dang su dung file");
                    }
                    
                }
                lstObjMyDownload.Remove(tempMyDownload);
                                         
            }

            isClickCell = false;
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            // Hiển thị lại Form nếu doubleclick vào icon dưới System tray
            Show();
            WindowState = FormWindowState.Normal;
        }

        private void Form1_Resize(object sender, EventArgs e)
        {
            // Nếu Form đang Minimize thì ẩn luôn Form
            if (FormWindowState.Minimized == WindowState)
                Hide();
        }

        private void contextMenuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            if (m_pLstView.Items.Count > 0)
            {
                try
                {
                    ixdSelect = m_pLstView.SelectedIndices[0];
                    tempMyDownload = lstObjMyDownload.ElementAt<MyDownload>(ixdSelect);
                    isClickCell = true;
                    m_pBtnResume.Enabled = true;

                    if (e.ClickedItem.Text.Equals("Open"))
                    {
                        string str = tempMyDownload.StrFilePath;
                        Process process = new Process();
                        process.StartInfo.FileName = str;
                        process.Start();
                    }
                    if (e.ClickedItem.Text.Equals("Stop"))
                    {
                        m_pBtnStop_Click(null, null);
                    }
                    if (e.ClickedItem.Text.Equals("Pause/Resume"))
                    {
                        m_pBtnResume_Click(null, null);
                    }
                    if (e.ClickedItem.Text.Equals("Delete"))
                    {
                        m_pBtnDelete_Click(null, null);
                    }
                    if (e.ClickedItem.Text.Equals("Delete all"))
                    {
                        m_pBtnDeleteAll_Click(null, null);
                    }
                    if (e.ClickedItem.Text.Equals("Detail"))
                    {
                        m_pLstView_DoubleClick(null, null);
                    }
                    if (e.ClickedItem.Text.Equals("Remove"))
                    {
                        tempMyDownload = lstObjMyDownload.ElementAt<MyDownload>(ixdSelect);
                        tempMyDownload.Stop();
                        m_pLstView.Items.Remove(m_pLstView.Items[ixdSelect]);
                        lstObjMyDownload.Remove(tempMyDownload);
                    }
                }
                catch (System.Exception ex)
                {
                    //MessageBox.Show("Chon lai nha!");
                }
            }
        }
        

        private void m_pBtnMinisize_Click_1(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
